package com.example.sd;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.File;
import java.nio.charset.Charset;

import cn.hutool.core.io.FileUtil;

public class MainActivity2 extends AppCompatActivity {
    public static final String[] PERMISSION_SDCARD = new String[]{
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    public static final int REQUEST_CODE_SDCARD = 1;

    public static final String TAG = "MainActivity2";

    File dir;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        // 获取的是外部存储的公有文件的路径，无须访问权限
//        dir = Environment.getExternalStorageDirectory();
        // getExternalStorageDirectory:/storage/emulated/0
//        Log.d(TAG, "getExternalStorageDirectory:"+dir.getAbsolutePath());
        // Environment.getExternalStoragePublicDirectory()方法获取的是外部存储的公共文件的路径，需要访问权限
        // getExternalStoragePublicDirectory:/storage/emulated/0/Download
        dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        Log.d(TAG, "getExternalStoragePublicDirectory:"+dir.getAbsolutePath());
        TextView msg = findViewById(R.id.msg);
        msg.setText(dir.getAbsolutePath());



        Button saveBtn = findViewById(R.id.save_btn);
        Button getGrant = findViewById(R.id.getGrant);
        getGrant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                permission();
            }
        });

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                performAction();
            }
        });

    }


    private void permission() {
        if(PermissionUtils.checkPermission(this,PERMISSION_SDCARD,REQUEST_CODE_SDCARD)){
            performAction();
        }
    }


    /**
     * 在 onRequestPermissionsResult() 方法中处理权限请求的结果。这个方法会在用户响应权限请求后被调用。你可以使用以下代码来处理结果：
     *
     * @param requestCode The request code passed in {@link # requestPermissions(
     * android.app.Activity, String[], int)}
     * @param permissions The requested permissions. Never null.
     * @param grantResults The grant results for the corresponding permissions
     *     which is either {@link android.content.pm.PackageManager#PERMISSION_GRANTED}
     *     or {@link android.content.pm.PackageManager#PERMISSION_DENIED}. Never null.
     *
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_SDCARD) {
            if(PermissionUtils.checkGrantResults(grantResults)){
                ToastUtils.show(this,"获取读写权限成功");
            }else{
                ToastUtils.show(this,"获取读写权限失败");
            }
        }
    }

    private void performAction() {
        try {
            // 执行外部存储操作，例如读取文件
            File file = new File(dir, "filename.txt");
            if (file.exists()) {
                // 处理文件读取的相关操作
                FileUtil.writeString("hello world",file, Charset.defaultCharset());
            } else {
                // 处理文件不存在的情况
                if(file.createNewFile()){
                    FileUtil.writeString("hello world",file,Charset.defaultCharset());
                }
            }
        } catch (Exception e) {
            // 处理异常情况
        }
    }
}